﻿using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TS2015.Models;
using Kendo.Mvc.Extensions;
using System.Data.Entity;
using System.IO;
using System.Data.Entity.Validation;

namespace TS2015.Areas.Admin.Controllers
{
 
    public class QuanTriTrangController : Controller
    {
        TS2015Context db = new TS2015Context();
        public ActionResult DanhSachTinTuc()
        {
            if (!CheckRole.IsRole("qtt_dstt", Session["Function"] as string[]))
                return Redirect("~/accessdenied.html");

            Database.SetInitializer<TS2015Context>(null);
            ViewBag.TheLoai = db.TbTheLoais.ToList();

            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }

        public ActionResult TheLoaiTinTuc()
        {
            if (!CheckRole.IsRole("qtt_tltt", Session["Function"] as string[]))
                return Redirect("~/accessdenied.html");

            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }

        public ActionResult Slide()
        {
            if (!CheckRole.IsRole("qtt_slide", Session["Function"] as string[]))
                return Redirect("~/accessdenied.html");

            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }

        public IEnumerable<TbTinTuc> TinNoiBat()
        {
            return db.TbTinTucs.Where(e => e.NoiBat == true);
        }
        public IEnumerable<TbTinTuc> TinNoiBat(int SoLuongTin)
        {
            if (SoLuongTin > 0)            
                return db.TbTinTucs.Where(e => e.NoiBat == true).Take(SoLuongTin);

            return db.TbTinTucs.Where(e => e.NoiBat == true);
        }

        public ActionResult ThemHoacSuaTinTuc(string id)
        {
            if (!CheckRole.IsRole("qtt_thstt", Session["Function"] as string[]))
                return Redirect("~/accessdenied.html");

            TbTinTuc item = new TbTinTuc();
            SelectList LoaiTinTuc = null;
            if (ModelState.IsValid)
            {                          
                if (id != null)
                {
                    var idTT=long.Parse(id);
                    item = db.TbTinTucs.First(e => e.MaTinTuc == idTT);
                    LoaiTinTuc = new SelectList(db.TbTheLoais.ToList(), "MaTheLoai", "TenTheLoai", item.MaTheLoai);
                }
                else
                    LoaiTinTuc = new SelectList(db.TbTheLoais.ToList(), "MaTheLoai", "TenTheLoai");

                ViewBag.TheLoai = LoaiTinTuc;
            }

            if (!Request.IsAjaxRequest())
                return View(item);
      
            return PartialView(item);
        }

        [HttpPost]
        public ActionResult ThemHoacSuaTinTuc(TbTinTuc item)
        {
            if (!CheckRole.IsRole("qtt_thstt", Session["Function"] as string[]))
                return Redirect("~/accessdenied.html");

            if (item != null && ModelState.IsValid)
            {
                item.NgayDang = DateTime.Now;
                string fileName = "";

                var files = Request.Files["AnhDaiDien"];
                if (files != null && files.ContentLength > 0)
                    try
                    {                      
                        // Kiểm tra nếu trình duyệt IE thì cách lấy tên file khác
                        if (Request.Browser.Browser == "IE")
                            fileName = Path.GetFileName(files.FileName);
                        else
                            fileName = files.FileName;
                        // Đổi tên ảnh tránh bị mất file khi trùng tên.
                        fileName = (DateTime.Now.ToString("MMddyyyyHHmmssfff") + "_" + fileName);
                        string path = Path.Combine(Server.MapPath("~/Uploads/img"), fileName);
                        item.AnhDaiDien = fileName;
                        files.SaveAs(path);
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Message = "Lỗi:" + ex.Message.ToString();
                    }

                //Nếu sửa tin tức
                if (item.MaTinTuc > 0)
                {
                    //Lấy ảnh đại diện cũ
                   string AnhDaiDien= db.TbTinTucs.AsNoTracking().First(e => e.MaTinTuc == item.MaTinTuc).AnhDaiDien;                                       

                    // Kiem tra co ảnh upload lên server ko
                   if (fileName!="" && AnhDaiDien != "")
                    {
                        // Xóa ảnh cũ
                        string fullPath = Request.MapPath("~/Uploads/img/" + AnhDaiDien);
                        if (System.IO.File.Exists(fullPath))
                            System.IO.File.Delete(fullPath);
                    }
                    else
                       item.AnhDaiDien = AnhDaiDien;
                    
                    db.Entry(item).State = EntityState.Modified;
                }
                // Thêm mới tin tức
                else
                    db.TbTinTucs.Add(item);
                // Lưu vào CSDL
                db.SaveChanges();
            }
            // cái đoạn này dùng để làm gì hả m?
            ViewBag.TheLoai = new SelectList(db.TbTheLoais.ToList(), "MaTheLoai", "TenTheLoai", item.MaTheLoai);
             

            TempData["Message"] = "Lưu thành công!";
            return RedirectToAction("DanhSachTinTuc");
            //if (!Request.IsAjaxRequest())
            //    return View(item);

            //return PartialView(item);
        }

        #region Thể loại tin tức
        public ActionResult Editing_ReadTheLoaiTT([DataSourceRequest] DataSourceRequest request)
        {
            if (!CheckRole.IsRole("qtt_tltt", Session["Function"] as string[]))
                return Redirect("~/accessdenied.html");

            var data = db.TbTheLoais;

            return Json(data.ToDataSourceResult(request));
        }

        [HttpPost]
        public ActionResult Editing_CreateTheLoaiTT([DataSourceRequest] DataSourceRequest request, TbTheLoai data)
        {
            //if (!CheckRole.IsRole("qtt_ctltt", Session["Function"] as string[]))
            //    return Redirect("~/accessdenied.html");

            if (data != null && ModelState.IsValid)
            {
                //string fileName = "";
                //var files =UploadAnh;
                //if (files != null && files.ContentLength > 0)
                //    try
                //    {
                //        // Kiểm tra nếu trình duyệt IE thì cách lấy tên file khác
                //        if (Request.Browser.Browser == "IE")
                //            fileName = Path.GetFileName(files.FileName);
                //        else
                //            fileName = files.FileName;
                //        // Đổi tên ảnh tránh bị mất file khi trùng tên.
                //        fileName = (DateTime.Now.ToString("MMddyyyyHHmmssfff") + "_" + fileName);
                //        string path = Path.Combine(Server.MapPath("~/Uploads/img"), fileName);
                //        data.Anh = fileName;
                //        files.SaveAs(path);
                //    }
                //    catch (Exception ex)
                //    {
                //        ViewBag.Message = "Lỗi:" + ex.Message.ToString();
                //    }

                db.TbTheLoais.Add(data);
                ViewBag.IDTheLoai = data.MaTheLoai;
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        [HttpPost]
        public ActionResult Editing_UpdateTheLoaiTT([DataSourceRequest] DataSourceRequest request, TbTheLoai data)
        {
            //if (!CheckRole.IsRole("qtt_utltt", Session["Function"] as string[]))
            //    return Redirect("~/accessdenied.html");

            if (data != null && ModelState.IsValid)
            {
                string fileName = "";
                var files = Request.Files["Anh"];
                if (files != null && files.ContentLength > 0)
                    try
                    {
                        // Kiểm tra nếu trình duyệt IE thì cách lấy tên file khác
                        if (Request.Browser.Browser == "IE")
                            fileName = Path.GetFileName(files.FileName);
                        else
                            fileName = files.FileName;
                        // Đổi tên ảnh tránh bị mất file khi trùng tên.
                        fileName = (DateTime.Now.ToString("MMddyyyyHHmmssfff") + "_" + fileName);
                        string path = Path.Combine(Server.MapPath("~/Uploads/img"), fileName);
                        data.Anh = fileName;
                        files.SaveAs(path);
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Message = "Lỗi:" + ex.Message.ToString();
                    }

                //Nếu sửa tin tức
                if (data.MaTheLoai > 0)
                {
                    //Lấy ảnh đại diện cũ
                    string OldAnh = db.TbTheLoais.AsNoTracking().First(e => e.MaTheLoai == data.MaTheLoai).Anh;
                     //Kiem tra co ảnh upload lên server ko
                    if (fileName != "" && OldAnh != "")
                    {
                         //Xóa ảnh cũ
                        string fullPath = Request.MapPath("~/Uploads/img/" + OldAnh);
                        if (System.IO.File.Exists(fullPath))
                            System.IO.File.Delete(fullPath);
                    }
                    else
                        data.Anh = OldAnh;
                }

                db.Entry(data).State = EntityState.Modified;
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        [HttpPost]
        public ActionResult Editing_DestroyTheLoaiTT([DataSourceRequest] DataSourceRequest request, TbTheLoai data)
        {
            //if (!CheckRole.IsRole("qtt_dtltt", Session["Function"] as string[]))
            //    return Redirect("~/accessdenied.html");

            if (data != null)
            {
                TbTheLoai itemdata = db.TbTheLoais.First(item => item.MaTheLoai == data.MaTheLoai);
                db.TbTheLoais.Remove(itemdata);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }

        #endregion

        #region Danh sách tin tức
        public ActionResult Editing_ReadTinTuc([DataSourceRequest] DataSourceRequest request)
        {
            //if (!CheckRole.IsRole("qtt_dstt", Session["Function"] as string[]))
            //    return Redirect("~/accessdenied.html");

            var data = db.TbTinTucs;

            return Json(data.ToDataSourceResult(request));
        }

        public ActionResult Editing_CreateTinTuc([DataSourceRequest] DataSourceRequest request, TbTinTuc data)
        {
            //if (!CheckRole.IsRole("qtt_ctt", Session["Function"] as string[]))
            //    return Redirect("~/accessdenied.html");

            if (data != null && ModelState.IsValid)
            {
                db.TbTinTucs.Add(data);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult Editing_UpdateTinTuc([DataSourceRequest] DataSourceRequest request, TbTinTuc data)
        {
            //if (!CheckRole.IsRole("qtt_udtt", Session["Function"] as string[]))
            //    return Redirect("~/accessdenied.html");

            if (data != null && ModelState.IsValid)
            {
                db.Entry(data).State = EntityState.Modified;
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult Editing_DestroyTinTuc([DataSourceRequest] DataSourceRequest request, TbTinTuc data)
        {
            //if (!CheckRole.IsRole("qtt_dttt", Session["Function"] as string[]))
            //    return Redirect("~/accessdenied.html");

            if (data != null)
            {                 
                TbTinTuc itemdata = db.TbTinTucs.First(item => item.MaTinTuc == data.MaTinTuc);
                db.TbTinTucs.Remove(itemdata);
                db.SaveChanges();
            }
            return Json("");
        }
        #endregion

        #region Danh sách Slide
        public ActionResult Editing_ReadSlide([DataSourceRequest] DataSourceRequest request)
        {
            //if (!CheckRole.IsRole("qtt_slide", Session["Function"] as string[]))
            //    return Redirect("~/accessdenied.html");

            var data = db.TbSlides;

            return Json(data.ToDataSourceResult(request));
        }

        public ActionResult CreateSlide(HttpPostedFileBase[] FileImport)
        {            
            bool state = false;
            string mess = "", fileName = "";
            

            if(FileImport==null)
                return Json(new { State = state, Message = "Bạn chưa chọn ảnh tải lên" });
            
            int count = 0;
            int len = FileImport.Count();
            foreach (var file in FileImport)
            {
                try
                {
                    if (Request.Browser.Browser == "IE")
                        fileName = Path.GetFileName(file.FileName);
                    else
                        fileName = file.FileName;

                    // Đổi tên ảnh tránh bị mất file khi trùng tên.
                    fileName = (DateTime.Now.ToString("MMddyyyyHHmmssfff") + "_" + fileName);
                    string path = Path.Combine(Server.MapPath("~/Uploads/Slide"), fileName);

                    TbSlide item = new TbSlide() { Anh = fileName, ThuTu = db.TbSlides.Count() + 1, MoTa = "" };

                    db.TbSlides.Add(item);
                    db.SaveChanges();

                    file.SaveAs(path);
                    count++;
                }
                catch 
                {
                    return Json(new { State = false, Message = "Thêm " + count + " slide thành công.\nCó " + (len-count) +" tệp không đúng định dạng"});
                }
            }
            if (count > 0)
            {
                mess = "Thêm " + count + " slide thành công";
                state = true;               
            }
            else
                mess = "Có lỗi khi thêm file";

            return Json(new { State = state, Message = mess });
        }                
        public ActionResult Editing_UpdateSlide([DataSourceRequest] DataSourceRequest request, TbSlide data)
        {
            //if (!CheckRole.IsRole("qtt_udslide", Session["Function"] as string[]))
            //    return Redirect("~/accessdenied.html");

            if (data != null && ModelState.IsValid)
            {
                db.Entry(data).State = EntityState.Modified;
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult Editing_DestroySlide([DataSourceRequest] DataSourceRequest request, TbSlide data)
        {
            //if (!CheckRole.IsRole("qtt_dtslide", Session["Function"] as string[]))
            //    return Redirect("~/accessdenied.html");

            if (data != null)
            {
                TbSlide itemdata = db.TbSlides.First(item => item.MaSlide == data.MaSlide);
                db.TbSlides.Remove(itemdata);
                db.SaveChanges();

                var physicalPath = Path.Combine(Server.MapPath("~/Uploads/Slide"), itemdata.Anh);

                // TODO: Verify user permissions

                if (System.IO.File.Exists(physicalPath))
                {
                    // The files are not actually removed in this demo
                    System.IO.File.Delete(physicalPath);
                }
            }
            return Json(ModelState.ToDataSourceResult());
        }
        #endregion
    }
}